<template>
<div style="height: 100%;">
  <el-form class="projectForm" ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px" style="height: 100%;">
    <el-tabs v-model="activeName" @tab-click="TabClick" style="height: 100%;">
      <el-tab-pane style="height: 100%;" label="1.选择作业人员" name="first">
        <el-row>
        <div class="task-distribution-basic">
          <div class="task-distribution-title col-lg-100">基本信息</div>
          <div class="task-distribution-property">
            <el-form-item label="项目名称" prop="fName">
              <el-input v-model="distProject.fName" type="textarea" />
            </el-form-item>

            <el-form-item label="项目标识码" prop="fProjectid">
              <el-input v-model="distProject.fProjectid" type="textarea" />
            </el-form-item>

            <el-form-item label="初始时间" prop="fCreatedate">
              <el-input v-model="distProject.fCreatedate" type="textarea" />
            </el-form-item>

            <el-form-item label="结束时间" prop="fEnddate">
              <el-input v-model="distProject.fEnddate" type="textarea" />
            </el-form-item>

            <el-form-item label="作业单位" prop="deptName">
              <el-input v-model="proDept.deptName" type="textarea" />
            </el-form-item>

            <el-form-item label="单位负责人" prop="leader">
              <el-input v-model="proDept.leader" type="textarea" />
            </el-form-item>
          </div>
        </div>
        <div class="task-distribution-user">
<!--          <div class="left-container">-->
<!--            <el-tree-->
<!--              :data="deptOptions"-->
<!--              :props="defaultProps"-->
<!--              :expand-on-click-node="false"-->
<!--              :filter-node-method="filterNode"-->
<!--              ref="tree"-->
<!--              default-expand-all-->
<!--              highlight-current-->
<!--              @node-click="handleNodeClick"-->
<!--            />-->
<!--          </div>-->
          <div class="right-container">
            <div class="task-distribution-title col-lg-100">外业核查员</div>
              <div class="task-distribution-property">
                <div class="task-user-item" v-for="(item,index) in wyUserList"  :rname="item.nickName"
                     :userid="item.userId" @click="chooseWy(0,item,wyUserList) " >
                  <div class="task-user-wrap" :class="{'selected':item.checked}">
                    <div><span class="task-content-text">姓名</span>
                      <span class="task-content-value">{{ item.nickName }}</span>
                    </div>
                    <div><span class="task-content-text">用户名</span>
                      <span class="task-content-value">{{ item.userName }}</span>
                    </div>
                    <div><span class="task-content-text">所属单位</span>
                      <span class="task-content-value">{{ proDept.deptName }}</span>
                    </div>
                    <div><span class="task-content-text">角色</span>
                      <span class="task-content-value">外业核查员</span>
                    </div>
                  </div>
                </div>
              </div>
          </div>
          <div class="right-container">
            <div class="task-distribution-title col-lg-100">内业审核员</div>
            <div class="task-distribution-property">
              <div class="task-user-item" v-for="(item,index) in nyUserList"  :rname="item.nickName"
                   :userid="item.userId" @click="chooseWy(1,item,nyUserList) " >
                <div class="task-user-wrap" :class="{'selected':item.checked}">
                  <div><span class="task-content-text">姓名</span>
                    <span class="task-content-value">{{ item.nickName }}</span>
                  </div>
                  <div><span class="task-content-text">用户名</span>
                    <span class="task-content-value">{{ item.userName }}</span>
                  </div>
                  <div><span class="task-content-text">所属单位</span>
                    <span class="task-content-value">{{ item.dept.deptName }}</span>
                  </div>
                  <div><span class="task-content-text">角色</span>
                    <span class="task-content-value">外业核查员</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        </el-row>
        <el-form-item size="large">
          <el-col>
            <el-button type="primary" circle @click="Next(2)" icon="el-icon-right"></el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane style="height: 100%;" label="2.举证任务分发" name="second">
        <el-row class="step2">
          <div class="task-distribution-basic">
            <div class="task-distribution-title col-lg-100">基本信息</div>
            <div class="task-distribution-property">
              <span>选择图层</span>
              <select id="datasourcesSelect" class="form-control"  @change="SelectLayer($event,'step2')">
                <option v-for="layItem in dist.layers" :value="layItem.f_layerid" >{{layItem.f_layerrname}}</option>
              </select>
              <span>选择图层</span>
              <select id="datasourcesSelect" class="form-control"  @change="SelectDistField($event,'step2')">
                <option v-for="fieldItem in currentLayer.distFields" :value="fieldItem" >{{fieldItem}}</option>
              </select>

              <el-table v-loading="loading" :data="currentLayer.distitems" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" type="index" width="50"></el-table-column>
                <el-table-column label="分类标识" align="center" prop="disttype" />
                <el-table-column label="数量" align="center" prop="count" />
                <el-table-column label="外业核查员" align="center" prop="wyuser" />
              </el-table>

            </div>
          </div>
          <div class="task-distribution-user">
            <div class="right-container">
              <div class="task-distribution-title col-lg-100">外业核查员</div>
              <div class="task-distribution-property">
                <div class="task-user-item" v-for="(item,index) in dist.wyUsers"  :rname="item.nickName"
                     :userid="item.userId" @click="chooseUser('step2',item,dist.wyUsers) " >
                  <div class="task-user-wrap" :class="{'selected':item.checked}">
                    <div><span class="task-content-text">姓名</span>
                      <span class="task-content-value">{{ item.nickName }}</span>
                    </div>
                    <div><span class="task-content-text">用户名</span>
                      <span class="task-content-value">{{ item.userName }}</span>
                    </div>
                    <div><span class="task-content-text">所属单位</span>
                      <span class="task-content-value">{{ item.dept.deptName }}</span>
                    </div>
                    <div><span class="task-content-text">角色</span>
                      <span class="task-content-value">外业核查员</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </el-row>
        <el-form-item size="large">
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(1)" icon="el-icon-back"></el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(3)" icon="el-icon-right"></el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane style="height: 100%;" label="3.审核任务分发" name="third">
        <el-row class="step3">
          <div class="task-distribution-basic">
            <div class="task-distribution-title col-lg-100">基本信息</div>
            <div class="task-distribution-property">
              <span>选择图层</span>
              <select id="datasourcesSelect" class="form-control"  @change="SelectLayer($event,'step3')">
                <option v-for="layItem in dist.layers" :value="layItem.f_layerid" >{{layItem.f_layerrname}}</option>
              </select>
              <span>选择图层</span>
              <select id="datasourcesSelect" class="form-control"  @change="SelectDistField($event,'step3')">
                <option v-for="fieldItem in currentLayer.distFields" :value="fieldItem" >{{fieldItem}}</option>
              </select>

              <el-table v-loading="loading" :data="currentLayer.distitems" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" type="index" width="50"></el-table-column>
                <el-table-column label="分类标识" align="center" prop="disttype" />
                <el-table-column label="数量" align="center" prop="count" />
                <el-table-column label="内业审核员" align="center" prop="nyuser" />
              </el-table>

            </div>
          </div>
          <div class="task-distribution-user">
            <div class="right-container">
              <div class="task-distribution-title col-lg-100">内业审核员</div>
              <div class="task-distribution-property">
                <div class="task-user-item" v-for="(item,index) in dist.nyUsers"  :rname="item.nickName"
                     :userid="item.userId" @click="chooseUser('step3',item,dist.nyUsers) " >
                  <div class="task-user-wrap" :class="{'selected':item.checked}">
                    <div><span class="task-content-text">姓名</span>
                      <span class="task-content-value">{{ item.nickName }}</span>
                    </div>
                    <div><span class="task-content-text">用户名</span>
                      <span class="task-content-value">{{ item.userName }}</span>
                    </div>
                    <div><span class="task-content-text">所属单位</span>
                      <span class="task-content-value">{{ item.dept.deptName }}</span>
                    </div>
                    <div><span class="task-content-text">角色</span>
                      <span class="task-content-value">内业审核员</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

          </div>
        </el-row>
        <el-form-item size="large">
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(2)" icon="el-icon-back"></el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" circle @click="Next(4)" icon="el-icon-right"></el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane style="height: 100%;" label="4.任务预览" name="fourth">
        <el-row class="step4">
          <mapShow v-if="showMap" :showMap="showMap"></mapShow>
          <div class="task-distribution-result padding-10-20">
            <div>
              <span>选择图层</span>
              <select id="datasourcesSelect" class="form-control"  @change="SelectLayer($event,'step4')">
                <option v-for="layItem in dist.layers" :value="layItem.f_layerid" >{{layItem.f_layerrname}}</option>
              </select>
            </div>
            <div class="task-layer">
              <a class="selected" type="wy">
                <el-radio v-model="preview.user" label="wy" @change="changeHandler">外业核查</el-radio>
<!--                <span class="task-layer-radio"></span>-->
<!--                <span>外业核查</span>-->
              </a>
              <div class="task-layer-legends">
                <div v-for="(item,index) in preview.wy.legends" :userid="item.userid">
                  <span>{{item.rname}}</span>
                  <span class='layer-legend' :style="item.style"></span>
                </div>
              </div>
            </div>
            <div class="task-layer">
              <a class="" type="ny">
                <el-radio v-model="preview.user" label="ny" @change="changeHandler">内业审核</el-radio>
<!--                <span class="task-layer-radio"></span>
                <span>内业审核</span>-->
              </a>
              <div class="task-layer-legends">
                <div v-for="(item,index) in preview.ny.legends" :userid="item.userid">
                  <span>{{item.rname}}</span>
                  <span class='layer-legend' :style="item.style"></span>
                </div>
              </div>
            </div>
          </div>
        </el-row>
        <el-form-item size="large">
          <el-col :span="12">
            <el-button type="primary" @click="Next(3)">上一步</el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" @click="Submit()">提交</el-button>
          </el-col>
        </el-form-item>
      </el-tab-pane>
    </el-tabs>
  </el-form>
</div>
</template>

<script>
import { addProject, getProject, updateProjectState } from '@/api/survey/project'
import {addLayerMeta} from '@/api/survey/layer'
import { getTaskJson, getLayerDist, saveTask, getLayerInfo, getFeatures, getLayerDistIds } from '@/api/survey/task'
import { getDept, listDept, listDeptExcludeChild, wyDeptTreeselect } from '@/api/system/dept'
import mapShow from '@/views/survey/project/mapShow'
import Bus from '@/utils/bus'

import Qs from "qs";

import {
  addProjectLayer,
  addProjectUnit,
  getUnitByPro,
  saveShpFile,
  uploadShpFile
} from '@/api/survey/basic'
import { getUserByDeptRole, listUser } from '@/api/system/user'
import { addSurvey } from '@/api/survey/survey'

export default {
  name: 'distTask',
  components:{mapShow},
  data(){
    return {
        showMap:false,
      // 遮罩层
      loading: false,
      dist:{
        wyUsers:[],
        nyUsers:[],
        layers:[],
        taskDetails:null
      },
      chooseLayerItems:[],
      preview:{
        user:'wy',
        wy:{
          legends:[]
        },
        ny:{
          legends:[]
        }
      },
      config:{
        taskDetails:{
          distNow:[],
        }
      },
      currentLayer:{
        currentLayerIndex:null,
        distFields:[],
        distField:null,
        count:null,
        distitems:[]
      },
      activeName: 'first',
      formData:{},
      rules: {},
      wyUserList:[],
      nyUserList:[],
      proDept:{
        // deptId:null,
        // deptName:null,
        // leader:null,
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
    }
  },
  props: {
    show: {
      type: Object,
      default: null
    },
    distProject:{
      type: Object,
      default: null
    }
  },
  mounted() {
    this.getUsers();
  },
  methods: {
    changeHandler(){
      let that=this;
      that.getLayerDetailFea(that.currentLayer.currentLayerIndex, that.currentLayer.distField, "step4");
    },
    SelectLayer(e,stepType){
      let that=this;
      that.currentLayer.currentLayerIndex = e.target.value;
      //根据图层id 获取图层详细内容
      for(let i in that.dist.layers){
        let layer=that.dist.layers[i];
        if(layer.f_layerid==that.currentLayer.currentLayerIndex) {
          that.currentLayer.distFields = that.dist.layers[i].f_distfields.split(",");
          that.currentLayer.currentLayerIndex = that.dist.layers[i].f_layerid;
          that.currentLayer.distField = that.currentLayer.distFields[0];
          if (stepType == "step4") {
            that.getLayerDetailFea(that.currentLayer.currentLayerIndex, that.currentLayer.distField, stepType);
          } else if (stepType == "step2" || stepType == "step3") {
            that.getLayerDetail(that.currentLayer.currentLayerIndex, that.currentLayer.distField, stepType);
          }
          //that.distLayer=layer;
        }
      }

    },
    SelectDistField(e,stepType){
      let that=this;
      that.currentLayer.distField = e.target.value;
      that.getLayerDetail(that.currentLayer.currentLayerIndex,that.currentLayer.distField,stepType);
  },
    chooseUser(stepType,item,userList){
      let that=this;
      let userid=item.userId;
      let rname=item.nickName;

     if(item.checked){
       item.checked=false;
     }else{
       item.checked=true;
       let distLayer = null;
       for (let i in that.config.taskDetails.distNow) {
         var tempDistLayer = that.config.taskDetails.distNow[i];
         if (tempDistLayer.layerid == that.currentLayer.currentLayerIndex) {
           distLayer = tempDistLayer;
           break;
         }
       }

       if(stepType=="step2"){
         for(let i in that.dist.wyUsers){
           if(that.dist.wyUsers[i]!=item){
             that.dist.wyUsers[i].checked=false;
           }
         }
         for(let i in that.chooseLayerItems){
           let distFieldValue=that.chooseLayerItems[i];
           for(let m in that.currentLayer.distitems){
             let disitem=that.currentLayer.distitems[m];
             if(disitem.disttype==distFieldValue){
               that.$set(that.currentLayer.distitems[m], 'wyuser', rname);
               break;
             }
           }

           let hasDistRecord = false;
           // if(!that.distLayer.wy){
           //   that.$set(that.distLayer, 'wy', {});
           //   that.$set(that.distLayer.wy, 'distrecord', []);
           // }
           for (let j in distLayer.wy.distrecord) {
             let distRecord = distLayer.wy.distrecord[j];
             if (distRecord.value == distFieldValue) {
               hasDistRecord = true;
               distRecord.userid = userid;
               distRecord.rname = rname;
               break;
             }
           }
           if (!hasDistRecord) {
             distLayer.wy.distrecord.push({
               value: distFieldValue, userid: userid, rname: rname});
           }
         }
         //that.chooseLayerItems=[];
       }else if(stepType=="step3"){
         for(let i in that.dist.nyUsers){
           if(that.dist.nyUsers[i]!=item){
             that.dist.nyUsers[i].checked=false;
           }
         }
         for(let i in that.chooseLayerItems){
           let distFieldValue=that.chooseLayerItems[i];
           for(let m in that.currentLayer.distitems){
             let disitem=that.currentLayer.distitems[m];
             if(disitem.disttype==distFieldValue){
               that.$set(that.currentLayer.distitems[m], 'nyuser', rname);
               break;
             }
           }
           let hasDistRecord = false;
           // if(!that.distLayer.ny) {
           //   that.$set(that.distLayer, 'ny', {});
           //   that.$set(that.distLayer.ny, 'distrecord', []);
           // }
           for (let j in distLayer.ny.distrecord) {
             let distRecord = distLayer.ny.distrecord[j];
             if (distRecord.value == distFieldValue) {
               hasDistRecord = true;
               distRecord.userid = userid;
               distRecord.rname = rname;
               break;
             }
           }
           if (!hasDistRecord) {
             distLayer.ny.distrecord.push({layerid:that.currentLayer.currentLayerIndex,
               value: distFieldValue, userid: userid, rname: rname});
           }
         }

         //that.chooseLayerItems=[];
       }
     }

    },
    saveStep(steptype){
      let that=this;
      if(steptype=="step2"){
        for(let i in that.distLayer.wy.distrecord){
          let item=that.distLayer.wy.distrecord[i];
          that.distNow.push({
            layerid:item.layerid,
            wy:{
              distfield:item.value,
            }
          })
        }
      }
    },
    chooseWy(code,item,userList){//code 0 外业 1 内业
      let that=this;
      if(item.checked){
        item.checked=false;
        if(code==0){
          that.dist.wyUsers.splice(that.dist.wyUsers.indexOf(item),1);
        }else{
          that.dist.nyUsers.splice(that.dist.wyUsers.indexOf(item),1);
        }
      }else{
        item.checked=true;
        if(code==0){
          that.dist.wyUsers.push(JSON.parse(JSON.stringify(item)));
          that.dist.wyUsers[that.dist.wyUsers.length-1].checked=false;
        }else{
          that.dist.nyUsers.push(JSON.parse(JSON.stringify(item)));
          that.dist.nyUsers[that.dist.nyUsers.length-1].checked=false;
        }
      }
    },
    getLayerDetailFea(layerid,distfield,stepType){
      let that=this;
      getLayerDist({
        layerid:layerid,
        distfield:distfield,
        type:"feature"
      }).then(obj => {
        if (obj.layerInfo) {
           let layer = obj.layerInfo;
          // let stateValue = layer.f_state;
          // let state = "state_" + stateValue;
          //that.currentLayer.count = obj.sqlcount[0].count;
          //that.currentLayer.distitems = obj.sqlfeatures;
         if(stepType=="step4"){
            that.preview.wy.legends=[];
            that.preview.ny.legends=[];
            let userColor = that.config.taskDetails.userColor;
            let layerid = layer.f_layerid;
            let distConfig = null;
            let distField = null;
            for (let i in that.config.taskDetails.distNow) {
              let distNowItem = that.config.taskDetails.distNow[i];
              if (distNowItem.layerid == layerid) {
                //判断当前预览为内业还是外业，ny,wy
                let layerType = that.preview.user;//20220924
                distConfig = distNowItem[layerType];
                distField = distConfig.distfield;
                //外业用户人员图例
                let wyuserids = distNowItem.wy.userid;
                for (let j in wyuserids) {
                  let useridTemp = wyuserids[j];
                  let indexTemp = userColor.userid.indexOf(useridTemp);
                  if (indexTemp >= 0) {
                    var colorTemp = userColor.color[indexTemp];
                    var rnameTemp = userColor.rname[indexTemp];
                    that.preview.wy.legends.push({
                      userid:useridTemp,
                      rname:rnameTemp,
                      style:"background-color:rgb(" + colorTemp.r + "," + colorTemp.g + "," + colorTemp.b + ")"
                    })

                  }
                }
                //内业用户人员图例
                let nyuserids = distNowItem.ny.userid;
                for (let j in nyuserids) {
                  let useridTemp = nyuserids[j];
                  let indexTemp = userColor.userid.indexOf(useridTemp);
                  if (indexTemp >= 0) {
                    let colorTemp = userColor.color[indexTemp];
                    let rnameTemp = userColor.rname[indexTemp];
                    that.preview.ny.legends.push({
                      userid:useridTemp,
                      rname:rnameTemp,
                      style:"background-color:rgb(" + colorTemp.r + "," + colorTemp.g + "," + colorTemp.b + ")"
                    })
                  }
                }
                break;
              }
            }
            //分发记录中是否存在该图层
            let features = obj.sqlfeatures;
           Bus.$emit('clearOverSource',null);
            for (let i in features) {
              let feature = features[i];
              let color = {r: 255, g: 255, b: 0};
              let distValue = feature[distField];
              let userid = -1;
              if (distValue!=null&&distValue!=undefined) {
                for (var j in distConfig.distrecord) {
                  var distRecord = distConfig.distrecord[j];
                  if (distValue == distRecord.value) {
                    userid = distRecord.userid;
                    break;
                  }
                }
                var index = userColor.userid.indexOf(userid);
                if (index >= 0) {
                  color = userColor.color[index];
                }
              }
              let params=[feature.geom,distValue,color]
              Bus.$emit('addPreviewFeatures', params);
            }
           Bus.$emit('zoomToOverSource', null);
          }
        }
      });
    },
    getLayerDetail(layerid,distfield,stepType){
      let that=this;
      getLayerDist({
        layerid:layerid,
        distfield:distfield,
        type:"distribution"
      }).then(obj => {
        if (obj.layerInfo) {
          let layer = obj.layerInfo;
          let stateValue = layer.f_state;
          let state = "state_" + stateValue;
          that.currentLayer.count = obj.sqlcount[0].count;
          that.currentLayer.distitems = obj.sqldistitems;

          if(stepType=="step2"||stepType=="step3") {
            // 记录分发图层信息到config
            let hasLayer = false;
            let distfield = that.currentLayer.distField;
            var distObjTemp = { distfield: distfield, distrecord: [] };
            for (let i in that.config.taskDetails.distNow) {
              var distLayer = that.config.taskDetails.distNow[i];
              if (distLayer.layerid == layer.f_layerid) {
                hasLayer = true;
                switch (stepType) {
                  case "step2":
                    distLayer.wy = distObjTemp;
                    break;
                  case "step3":
                    distLayer.ny = distObjTemp;
                    break;
                }
                break;
              }
            }
            if (!hasLayer) {
              var objTemp = { layerid: layer.f_layerid };
              switch (stepType) {
                case "step2":
                  objTemp.wy = distObjTemp;
                  break;
                case "step3":
                  objTemp.ny = distObjTemp;
                  break;
              }
              that.config.taskDetails.distNow.push(objTemp);
            }
          }
        }
      });
    },
    getProjectJson(stepType){
      let that=this;
      //根据项目id获取项目详细信息
      getTaskJson({
        fProjectid:that.distProject.fProjectid,
      }).then(res => {
        that.dist.taskDetails = res;
        that.dist.layers = JSON.parse(that.dist.taskDetails.f_layer.value);
        that.currentLayer.distFields = that.dist.layers[0].f_distfields.split(",");
        that.currentLayer.currentLayerIndex = that.dist.layers[0].f_layerid;
        that.currentLayer.distField = that.currentLayer.distFields[0];
        //that.distLayer=that.dist.layers[0];
        //根据图层id 获取图层详细信息
        if(stepType=="step4"){
          that.getLayerDetailFea(that.currentLayer.currentLayerIndex, that.currentLayer.distField,stepType);
        }else if(stepType=="step2"||stepType=="step3"){
          that.getLayerDetail(that.currentLayer.currentLayerIndex, that.currentLayer.distField,stepType);
        }
      });
    },
    getUsers() {
      let that = this;
      //根据项目id获取单位id
      getUnitByPro({ fProjectid: that.distProject.fProjectid }).then(res => {
        if (res.code == 200) {
          that.proDept.deptId = res.rows[0].fUnitid;
          getDept(that.proDept.deptId).then(response => {
            that.proDept = response.data;
          });

          getUserByDeptRole({
            deptId: that.proDept.deptId,
            roleName: "外业人员"
          }).then(res => {
            if (res.code == 200) {
              that.wyUserList = res.rows;
              that.dist.wyUsers=[];
              for (let i in that.wyUserList) {
                that.$set(that.wyUserList[i], 'checked', false);
                //that.deptList[i].checked=false;
              }
            }
          });
          getUserByDeptRole({
            deptId: that.proDept.deptId,
            roleName: "内业审核人员"
          }).then(res => {
            if (res.code == 200) {
              that.nyUserList = res.rows;
              that.dist.nyUsers=[];
              for (let i in that.nyUserList) {
                that.$set(that.nyUserList[i], 'checked', false);
                //that.deptList[i].checked=false;
              }
            }
          });
        }
        });


    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let that=this;
      that.chooseLayerItems =selection.map(item => item.disttype);
      that.single = selection.length!==1
      that.multiple = !selection.length
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    /** 查询部门列表 */
    getDeptList() {
      let that=this;
      listDept(this.queryParams).then(response => {
        //that.deptList = that.handleTree(response.data, "deptId");
        that.deptList = response.data;
        for(let i in that.deptList){
          that.$set(that.deptList[i],'checked',false);
          //that.deptList[i].checked=false;
        }
      });
    },
    async Submit(){
      let that=this;
      for(let i in that.config.taskDetails.distNow){
        let distLayer=that.config.taskDetails.distNow[i];
        let layerid=distLayer.layerid;
        let wyDist=distLayer.wy;
        let nyDist=distLayer.ny;
        let wydistfield=null;
        let nydistfield=null;
        if(wyDist){
          wydistfield=wyDist.distfield;
        }
        if(nyDist){
          nydistfield=nyDist.distfield;
        }
        await that.asyncSubmit(layerid,wydistfield,nydistfield,wyDist,nyDist);
      }
      //20221009 更新项目和图层分发状态
      updateProjectState({
        fProjectid:that.distProject.fProjectid
      }).then(res => {
        let stateLayer=res.layer;
        let stateProject=res.project;
      })
      that.show.showDistTask=false;
    },
    asyncSubmit(layerid,wydistfield,nydistfield,wyDist,nyDist){
      let that=this;
      //获取layerid下所有featureid对应distvalue
      return new Promise((resolve, reject) => {
        getLayerDistIds({
          layerid: layerid,
          wydistfield: wydistfield,
          nydistfield: nydistfield
        }).then(res => {
          let wyFeatureIds = res.wy_sqldistids;
          let nyFeatureIds = res.ny_sqldistids;
          let paramList = [];
          if(wyDist!=null) {
            //let distrecord = wyDist.distrecord != null ? wyDist.distrecord : null;
            let distrecord = wyDist.distrecord;
            for(let j in distrecord) {
              let record = distrecord[j];
              let value = record.value != null ? record.value : null;
              let featureids = wyFeatureIds.filter((ev) => {
                return ev.disttype == value;
              });
              if(featureids.length > 0) {
                for (let indexFea in featureids) {
                  let featureid = featureids[indexFea].featureid;
                  let wyuserid = record.userid != null ? record.userid : null;
                  let upsertParam = {
                    fLayerid: layerid,
                    fFeatureid: featureid,
                    fWyUserid: wyuserid,
                    fNyUserid: -1,
                    fStatusid:1
                  }
                  paramList.push(upsertParam);
                }
              }
            }
          }
          if (nyDist!=null) {
            //let distrecord = nyDist.distrecord != null ? nyDist.distrecord : null;
            let distrecord = nyDist.distrecord;
            for(let j in distrecord) {
              let record = distrecord[j];
              let value = record.value != null ? record.value : null;
              let featureids = nyFeatureIds.filter((ev) => {
                return ev.disttype == value;
              });
              if(featureids.length > 0) {
                for(let indexFea in featureids) {
                  let featureid = featureids[indexFea].featureid;
                  let nyuserid = record.userid != null ? record.userid : null;
                  let surveyitem = paramList.filter((ev) => {
                    return ev.fLayerid == layerid && ev.fFeatureid == featureid;
                  });
                  if (surveyitem.length > 0) {
                    surveyitem[0].fNyUserid = nyuserid;
                  } else {
                    let upsertParam = {
                      fLayerid: layerid,
                      fFeatureid: featureid,
                      fWyUserid: nyuserid,
                      fNyUserid: -1,
                      fStatusid:1
                    }
                    paramList.push(upsertParam);
                  }
                }
              }
            }
          }
          //保存
          addSurvey(paramList).then(res => {
            if (res.code == 200) {
              resolve();
            }
          });
        });
      })
    },
    //单位选择
    changeCheckDept(e,index,item){
      let that=this;
      that.dept=item;
      for(let i in that.deptList){
        let item0=that.deptList[i];
        if(parseInt(i)==index)
          item0.checked=true;
        else
          item0.checked=false;
      }
    },
    //字段选择
    changeCheck(e,attr,item){
      let that=this;
      let checkflag = e.currentTarget.getAttribute("type");
      if (checkflag == "checked") {
        e.currentTarget.setAttribute("type", "unchecked");
        item[attr]=false;
      }
      if (checkflag == "unchecked") {
        e.currentTarget.setAttribute("type", "checked");
        item[attr]=true;
      }
    },
    //图层选择
    changeIndex(index) {
      this.fieldMap.selectLayerIndex = index;
      //默认显示第一个
      this.fieldMap.selectLayerName=this.fieldMap.layers[index].name;
      for(let i in this.fieldMap.layers){
        if(i==index)
          this.fieldMap.layers[index].visible=true;
        else
          this.fieldMap.layers[i].visible=false;
      }
    },
    saveFields(){
      let that=this;
      for(let i in that.fieldMap.layers){
        let layer=that.fieldMap.layers[i];
        let fields=layer.fields;
        let fieldNames=[];
        let showFields = [];
        let surveryFields = [];
        let distFields = [];
        for(let j in fields) {
          let field = fields[j];
          fieldNames.push(field.name);
          if (field.show)
            showFields.push(field.name);
          if(field.survey)
            surveryFields.push(field.name);
          if(field.dist)
            distFields.push(field.name);
        }
        that.config.layerlist[i]= {
          fName: layer.name,
          fRname: layer.name,
          fLayertype:layer.type,
          fFields: JSON.stringify(fieldNames),
          fShowfields: JSON.stringify(showFields.toString()),
          fSurveyfields: JSON.stringify(surveryFields.toString()),
          fDistfields: JSON.stringify(distFields.toString())
        }
      }
    },
    TabClick(tab) {
      let that = this
      that.Next(tab.index - 0 + 1)
    },
    Next(index) {
      let that = this
      switch (index) {
        case 1:
          that.activeName = 'first'
          break
        case 2://进入外业
          this.getProjectJson("step2");
          that.activeName = 'second'
          break;
        case 3:
          this.getProjectJson("step3");
          that.activeName = 'third'
          break;
        case 4:
          //预览
          this.showMap=true;
          let userColor = {
            userid: [],
            rname: [],
            color: []
          };
          for (let i in that.config.taskDetails.distNow) {
            let userids = [];
            let layerDistNow = that.config.taskDetails.distNow[i];
            for (let j in layerDistNow.wy.distrecord) {
              let item = layerDistNow.wy.distrecord[j];
              let userid = item.userid;
              let rname = item.rname;
              if (userColor.userid.indexOf(userid) >= 0) {
              } else {
                userColor.userid.push(userid);
                userColor.rname.push(rname);
                userColor.color.push({
                  r: Math.round(Math.random() * 255),
                  g: Math.round(Math.random() * 255),
                  b: Math.round(Math.random() * 255)
                });
              }
              if (userids.indexOf(userid) >= 0) {
              } else {
                userids.push(userid);
              }
            }
            layerDistNow.wy.userid = userids;
            userids = [];
            for (let j in layerDistNow.ny.distrecord) {
              let item = layerDistNow.ny.distrecord[j];
              let userid = item.userid;
              let rname = item.rname;
              if (userColor.userid.indexOf(userid) >= 0) {
              } else {
                userColor.userid.push(userid);
                userColor.rname.push(rname);
                userColor.color.push({
                  r: Math.round(Math.random() * 255),
                  g: Math.round(Math.random() * 255),
                  b: Math.round(Math.random() * 255)
                });
              }
              if (userids.indexOf(userid) >= 0) {
              } else {
                userids.push(userid);
              }
            }
            layerDistNow.ny.userid = userids;
          }
          that.config.taskDetails.userColor = userColor;
          this.getProjectJson("step4");
          that.activeName = 'fourth'
          break

      }
    },

    handleFilUploadSuccess(res, file, fileList) {
      console.log(res, file, fileList)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    // 文件上传成功时的函数
    fileChange(file) {
      let that = this
      this.fileList = [];
      let existFile = this.fileList.slice(0, this.fileList.length - 1).find(f => f.name === file.name)//如果文件名重复
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        this.fileList.pop()
      } else {
        this.fileList.push(file)
      }


      let fd = new FormData()
      that.fileList.forEach(item => {
        //文件信息中raw才是真的文件
        fd.append('files', item.raw)
      })

      uploadShpFile(fd).then(res => {
        if (res.status === "success") {
          if (res.queryData.length > 0) {
            that.fieldMap.layerNames = [];
            that.fieldMap.layers = [];
            let shps = res.queryData;
            that.shpPath=res.url;
            for (let i in shps) {
              let props = shps[i].data.props;
              let name = shps[i].data.name;
              let a=shps[i].data.type.split(".");
              let type=a[a.length-1];
              that.fieldMap.layerNames.push(name);
              let fields = [];
              if (props.length > 0) {
                let prop = props[0];
                let format = new ol.format.WKT()
                let feature = format.readFeature(prop.the_geom);
                for (let fieldname in prop) {
                  fields.push({
                    name: fieldname,
                    show: true,
                    survey: true,
                    dist: true
                  });
                }
              }
              that.fieldMap.layers.push({
                name: name,
                type:type,
                fields: fields,
                visible: false
              });
            }
            //默认显示第一个
            that.fieldMap.selectLayerIndex = 0;
            that.fieldMap.selectLayerName = that.fieldMap.layers[0].name;
            //that.fieldMap.fieldNames=that.fieldMap.layers[0].fields;
            that.fieldMap.layers[0].visible = true;
          }
          this.$message.success('上传成功')
          //this.mcShow.uploadshp = 'close'
        } else {
          this.$message.error('失败')
        }
      });
    },
  }
}
</script>

<style scoped>
.task-distribution-basic{
  border: 1px solid #3e3e3e;
  float: left;
  padding: 10px 20px;
  width: 30%;
  height: 100%;
  overflow: auto;
}
.task-distribution-property .el-form-item__label{
  float: left !important;
}
.task-distribution-user{
  border: 1px solid #3e3e3e;
  float: left;
  height: 100%;
  width: 70%;
  overflow: auto;
}
.task-distribution-title {
  color: #094871;
  font-size: 16px;
  font-weight: bold;
  line-height: 30px;
}
.task-distribution-property .task-user-item {
  display: inline-block;
  line-height: 30px;
  padding: 20px;
}
.task-distribution-user .task-user-wrap {
  padding-right: 30px;
  cursor: pointer;
  background-color: #e2f4ff;
}
.task-user-wrap {
  border: 1px solid #ddd;
  border-radius: 4px;
  box-shadow: 0px 0px 5px #ddd;
}
.task-content-text {
  font-weight: bold;
  min-width: 40%;
  margin-right: 20px;
  display: inline-block;
}
.task-distribution-user .selected {
  background: url(~@/assets/images/icon/check-true.png) no-repeat right top #e2f4ff;
  border: 1px solid #0b0;
  box-shadow: 0px 0px 5px #0b0;
}
.task-distribution-user .task-user-wrap>div {
  padding: 0px 10px;
}
. step2 .task-distribution-basic{
  width: 60% !important;
}
. step2 .task-distribution-user{
  width: 40% !important;
}
::v-deep .el-tabs__content{
  height:100%;
}
.el-tab-pane,.el-row{
  height:90%
}
::v-deep .step4 .el-form-item__content{
  position: absolute;
  right: 0;
}
.task-distribution-result{
  left: 42px;
  position: absolute;
  z-index: 1;
  line-height: 30px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0px 0px 5px #bbb;
  padding: 10px 20px;
}

.task-layer-legends .layer-legend {
  width: 70px;
  height: 30px;
  border: 1px solid #000;
}

.task-layer-legends span {
  padding: 0px 10px;
  display: inline-block;
  vertical-align: middle;
}

.task-distribution-result .task-layer-radio {
  width: 30px;
  height: 30px;
  cursor: pointer;
  background: url(~@/assets/images/icon/radio.png) center no-repeat;
}
</style>
